using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using NGen;
using NGen.Managers.Particle;

namespace XNAGameDemo.Particles
{
	public class ExampleParticleSystem : ParticleSystem
	{
		private float m_emissionLeftover;

		public ExampleParticleSystem(Vector2 p_location) {
			EmitterLocation = p_location;
			m_lTextures.Add(GameEngine.GameContent.Load<Texture2D>("Content\\Particles\\star"));
			m_lTextures.Add(GameEngine.GameContent.Load<Texture2D>("Content\\Particles\\diamond"));
			m_lTextures.Add(GameEngine.GameContent.Load<Texture2D>("Content\\Particles\\circle"));
		}

		public override void Update(GameTime p_gameTime) {
			int total = 200;

			m_emissionLeftover += (float)(total * p_gameTime.ElapsedGameTime.TotalSeconds);

			for(; m_emissionLeftover > 1; m_emissionLeftover-=1) {
				m_lParticles.Add(GenerateNewParticle());
			}


			for(int particle = 0; particle < m_lParticles.Count; particle++) {
				if(m_lParticles[particle].Update(p_gameTime)){
					m_lParticles.RemoveAt(particle);
					particle--;
				}
			}
		}

		protected override Particle GenerateNewParticle() {

			Texture2D texture = m_lTextures[GameEngine.Random.Next(m_lTextures.Count)];
			Vector2 position = EmitterLocation;
			Vector2 velocity = new Vector2(
				 (float)(GameEngine.Random.NextDouble() * 100f - 50f),
				 (float)(GameEngine.Random.NextDouble() * 100f - 50f));
			float angle = 0;
			float angularVelocity = 0.1f * (float)(GameEngine.Random.NextDouble() * 100f - 50f);
			Color color = new Color(
				(float)GameEngine.Random.NextDouble(),
				(float)GameEngine.Random.NextDouble(),
				(float)GameEngine.Random.NextDouble());
			float size = (float)GameEngine.Random.NextDouble();

			return new ExampleParticle(texture, position, velocity, angle, angularVelocity, color, size);
		}

		public override void Draw(SpriteBatch p_spriteBatch) {
			foreach(var particle in m_lParticles)
				particle.Draw(p_spriteBatch);
		}
	}
}